package com.demo2do.boyle.client.web.controller.task;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.entity.task.TaskDto;
import com.demo2do.boyle.client.service.AdvertisementService;
import com.demo2do.boyle.client.service.CustomerMessageService;
import com.demo2do.boyle.client.service.CustomerService;
import com.demo2do.boyle.client.service.SocialAccountService;
import com.demo2do.boyle.client.service.TaskService;
import com.demo2do.boyle.client.service.VariableService;
import com.demo2do.boyle.common.entity.AuditStatus;
import com.demo2do.boyle.common.entity.advertisement.Advertisement;
import com.demo2do.boyle.common.entity.customer.Customer;
import com.demo2do.boyle.common.entity.customer.message.Type;
import com.demo2do.boyle.common.entity.customer.social.SocialAccount;
import com.demo2do.boyle.common.entity.system.Variable;
import com.demo2do.boyle.common.entity.task.Task;
import com.demo2do.core.entity.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Page;
import com.demo2do.core.web.resolver.Secure;

@Controller
@RequestMapping("/tasks")
public class TaskController {
	
	/** mapping table: variable	id **/
	private static final Integer PROPERTY_TYPE = 1;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private CustomerMessageService customerMessageService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private AdvertisementService advertisementService;
	
	@Autowired
	private SocialAccountService socialAccountService;
	
	@Autowired
    private VariableService variableService;
	
	
	private static final Logger logger = LoggerFactory.getLogger(TaskController.class);
	
	/**
	 * List all the task
	 * 
	 * @param customerId
	 * @param taskStatus
	 * @param page
	 * @return
	 */
	@RequestMapping("")
	@ResponseBody
	public String list(@Secure(property = "id") Integer customerId, 
					   @RequestParam( value = "status", required = false) String status, 
					   Page page) {
		
		Result result = new Result();
		
		try {
			Customer customer = customerService.load(Customer.class, customerId);
			List<Task> tasks = taskService.listByCustomer(customer, status, page);
			List<TaskDto> taskDtos = new ArrayList<TaskDto>();
			for(Task task : tasks) {
				taskDtos.add(new TaskDto(task));
			}
			result.success().data("taskDtos", taskDtos).data("customer", customer);
			
		} catch (Exception e) {
			logger.info("list()", e);
			result.fail().message("服务器异常");
		}
		
		return JsonUtils.toJsonString(result);
	}
	
	
	/**
	 * Create a task
	 * @param customerId
	 * @param advertisementId
	 * @return
	 */
	@RequestMapping("/create")
	@ResponseBody
	public String create(@Secure(property = "id") Integer customerId,
						 @RequestParam( value = "customerId", required = false) Integer id,
						 @RequestParam("advertisementId") Integer advertisementId) {
		Result result = new Result();
		
		try {
			Customer customer = customerService.load(Customer.class, customerId);
			Advertisement advertisement = advertisementService.load(Advertisement.class, advertisementId);
			
			if (customer.getAuditStatus() == AuditStatus.AUDITING) {
				result.setCode("101");
				result.message("请先等待用户审核通过！");
				
			}else{
				
				SocialAccount socialAccount = socialAccountService.querySocialAccount(customer,advertisement.getSocialType());
				
				if (socialAccount == null) {
					result.setCode("101");
					result.data("url", "/"+customer.getId()+"/profile/social-accounts/add");
					result.message("请先添加" + advertisement.getSocialType().getDescription() + "账号！");
				} else if(socialAccount.getAuditStatus() == AuditStatus.AUDITING){
					result.setCode("101");
					result.message("请先等待" + advertisement.getSocialType().getDescription() + "账号通过审核！");
				}else{
					Variable variable = variableService.queryObjectForId(PROPERTY_TYPE);
					taskService.create(customer, advertisement,variable);
					customerMessageService.create(customer, Constant.CUSTOMER_MESSAGE_TASK_CREATE, Type.TASK);
					result.success().message("创建任务成功");
				}
			}
			
			
		} catch (Exception e) {
			logger.info("create()", e);
			result.fail().message("服务器异常");
		}
		
		return JsonUtils.toJsonString(result);
	}
	
	
	/**
	 * Load task by id
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/{id}")
	@ResponseBody
	public String getTask(@PathVariable("id") Integer id) {
		
		Result result = new Result();
		
		try {
			Task task = taskService.load(Task.class, id);
			TaskDto taskDto = new TaskDto(task);
			result.success().data("taskDto", taskDto);
		} catch(Exception e) {
			logger.info("getTask()", e);
			result.fail().message("服务器异常");
		}
		
		return JsonUtils.toJsonString(result);
	}
	
	/**
	 * 
	 * @param id
	 * @param screenshot
	 * @return
	 */
	@RequestMapping( value = "/{id}/upload-screenshot", method = RequestMethod.POST)
	@ResponseBody
	public String uploadScreenShot(@Secure(property = "id") Integer customerId, @PathVariable("id") Integer id, @RequestParam("screenshot") String screenshot) {
		Result result = new Result();
		
		try {
			
			Customer customer = customerService.load(Customer.class, customerId);
			
			Task task = taskService.load(Task.class, id);
			
			taskService.update(task.uploadScreenshot(screenshot));
			
			customerMessageService.create(customer, Constant.CUSTOMER_MESSAGE_TASK_UPLOAD, Type.TASK);
			
			result.success().message("上传认证图片成功！");
			
		} catch (Exception e) {
			logger.info("uploadScreenshot()", e);
			result.fail().message("服务器异常");
		}
		
		return JsonUtils.toJsonString(result);
	}
	
}
